package beanCopy;

import cn.hutool.core.bean.BeanUtil;
import jdk8.User;
import lombok.SneakyThrows;
import net.sf.cglib.beans.BeanCopier;
import util.T;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * bean复制工具类
 * 使用cglib的BeanCopier实现性能较好
 *
 * @author zhoujie
 * @date 2020-08-07
 */
public class BeanUtils {
    private BeanUtils() {
    }

    private static final Map<String, BeanCopier> BEAN_COPIERS = new ConcurrentHashMap<>();

    @SneakyThrows
    public static <T> T copy(Object source, Class<T> tClass) {
        if (Objects.isNull(source)) {
            return null;
        }
        String key = genKey(source.getClass(), tClass);
        BeanCopier beanCopier = BEAN_COPIERS.computeIfAbsent(key, k -> BeanCopier.create(source.getClass(), tClass, false));
        T t = tClass.newInstance();
        beanCopier.copy(source, t, null);
        return t;
    }

    private static String genKey(Class<?> srcClazz, Class<?> destClazz) {
        return srcClazz.getName() + destClazz.getName();
    }

    public static void main(String[] args) {
        User u=new User(1,"SKY");
        User u2 = BeanUtils.copy(u, User.class);
        System.out.println(u2);
    }
}
